package com.example.tests;

import static com.example.fw.RandomizeHelper.getRandomNumbers;
import static org.testng.AssertJUnit.assertTrue;

import org.testng.AssertJUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.example.fw.User;

public class SignupTest extends TestBase
{
	User user = new User();
	User admin = new User();

	@BeforeClass
	public void createUser()
	{
		String userName = "testuser" + getRandomNumbers(3);
		user.setLogin(userName)
				.setEmail(userName + "@localhost.localdomain")
				.setPassword("123456");

		admin.setLogin(app.getProperty("mantis.admin.login"))
				.setEmail(app.getProperty("mantis.admin.email"))
				.setPassword(app.getProperty("mantis.admin.password"));

		if (!app.getJamesHelper().doesUserExist(user.getLogin()))
			app.getJamesHelper().createUser(user.getLogin(), user.getPassword());
	}

	@AfterClass
	public void cleanUp()
	{
		if (app.getJamesHelper().doesUserExist(user.getLogin()))
			app.getJamesHelper().deleteUser(user.getLogin());

		app.getAccountHelper().deleteCreatedUser(admin, user);
	}

	@Test
	public void newUserShouldSignup()
	{
		app.getAccountHelper().signup(user);

		if ("yes".equals(app.getProperty("check.mail")))
		{
			app.getAccountHelper().login(user);
			assertTrue(app.getAccountHelper().isloggedIn(user));
		}
		if ("yes".equals(app.getProperty("check.ui")))
		{
			assertTrue(app.getAccountHelper().isUserCreated(admin, user));
		}
		if ("yes".equals(app.getProperty("check.db")))
		{
			assertTrue(app.getHibernateHelper().isUserCreated(user));
		}
	}

	@Test(enabled = false)
	public void existingUserShouldNotSignup()
	{
		try
		{
			app.getAccountHelper().signup(user);
		}
		catch (Exception e)
		{
			assertTrue(e.getMessage().contains("That username is alread being used"));
		}
		AssertJUnit.fail("Exception expected");
	}
}
